import { Injectable } from '@angular/core';
import {HttpClient, HttpErrorResponse, HttpHeaders} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import {ErrorObservable} from 'rxjs/observable/ErrorObservable';
import { catchError, retry } from 'rxjs/operators';

import url from './url';
export interface Config {
  heroesUrl: string;
  textfile: string;
}

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/x-www-form-urlencoded',
  })
};
@Injectable()
export class MyHttpService {
  constructor(private http: HttpClient) { }
  getUrl(params) {
    return this.http.get(url.test, {params: params}).pipe(
      retry(3),
      catchError((err) => this.handleError(err))
    );
  }
  saveUrl(params) {
    return this.http.post(url.user, params, httpOptions).pipe(
      retry(3),
      catchError((err) => this.handleError(err))
    );
  }
  private handleError(error: HttpErrorResponse) {
    console.log(this);    // 此时的this指向
    const code = error['status'];
    if (code === 401 || code === 417) {
    }
    const err = {url: error['url'], status: error['status'], msg: error['error'].msg};
    return new ErrorObservable(err);
  }
}
